<template>
  <Modal
      :show="show"
      title="菜单授权"
      @ok="handleOk"
      @cancel="handleCancel"
  >
    <n-tree
        key-field="menu_id"
        label-field="menu_name"
        :data="data"
        accordion
        :checkable="true"
        :check-on-click="true"
        :default-checked-keys="rowKeys"
        @update:checked-keys="handleCheck"
    ></n-tree>
  </Modal>
</template>

<script lang="ts">
export default {
  name: "RoleMenuModal"
}
</script>

<script setup lang="ts">
import {onMounted, ref} from "vue"
import Modal from '@/components/Modal.vue'
import {ums_menu_parentList, ums_role_menuImpower} from '@/api/ums'
import {RoleListType} from '@/view/system/role/RoleType'
import {UmsparentListRes} from '@/type/ums'
import useMsg from '@/hooks/useMsg'

const {success, error} = useMsg()

const formData = ref<RoleListType>()

const show = ref<boolean>(false)

const data = ref<UmsparentListRes[]>([])

const rowKeys = ref<string[]>([])

const init = (list: string[], row: RoleListType) => {
  rowKeys.value = []
  data.value = []
  formData.value = undefined
  //  查询所有菜单
  ums_menu_parentList().then(res => {
    if (res.code === 200) {
      data.value = res.data
      show.value = true
      formData.value = row
      rowKeys.value = list
    }
  })
}

const handleCheck = (rows: string[]) => {
  rowKeys.value = rows
}

const handleOk = () => {
  const list = rowKeys.value.map(item => ({
    menuId: item,
    roleId: formData.value!.roleId
  }))
  ums_role_menuImpower({
    list,
    roleId: formData.value!.roleId
  }).then(res => {
    if (res.code === 200){
      show.value = false
      success(res.message)
    }else{
      show.value = false
      error(res.message)
    }
  })
}

const handleCancel = () => {
  show.value = false
}

defineExpose({
  init
})

onMounted( () => {
} )
</script>

<style scoped lang="scss">

</style>
